TMM4175 Polymer Composites

Home About Python Links Table of Contents

Python

Python is free, available on virtually any platforms and operating systems, the language syntax is consider as relatively easy to learn, documentation, tutorials and examples are comprehensive, and finally, Python seems to conquer much ground across all fields of scientific and general computing. If you are completely new to both programming and Python, you may visit python.org and take a look at Python for beginners

Installation

The official implementation of Python is found at https://wiki.python.org/moin/BeginnersGuide/Download. However, you will need several added packages for this course, such as numpy and matplotlib, a process that needs a little bit of work.

If you do not have any particular skills, or interest in maintaining your custom Python implementation, a great way to get all you need running on your computer is to download and install Anaconda. It is free, and works on Windows, Mac OS, and Linux. When you install Anaconda, you get Spyder (a Matlab-looking interface) as well as the the Jupyter Notebook interface, hundreds of other packages, and the Anaconda Navigator for maintaining everything. Make sure to install the Python 3.x version of Anaconda. Download Anaconda.

Python in TMM4175 Polymer Composites

The following sections introduce frequently used data structures and methods in Polymer Composites. For a more in-depth and through understanding of the topics, please read the relevant documentation and/or look up relevant tutorials. See also the videos on using Jupyter Notebooks (on Blackboard)

Dictionaries

Python codes without the data structure dictionaries are nearly inconceivable. A dictionary is an associative array where keys of the dictionary are associated to respective values. You may think of the dictionary as a record-like data structure able to store mixed data such as material properties. For instance, some relevant properties of a fiber are name, density, Young’s modulus and tensile strength. A dictionary for one type of fiber can be as:

In [1]:
fiber1={'name':'E-glass' , 'rho':2.55 , 'E': 72.5 , 'TS':3400.0}

Values are accessed by keys. In the following example, name is one of the keys:

In [2]:
fiber1['name']
Out[2]:
'E-glass'

Iteration over the dictionary:

In [3]:
for key in fiber1:
    print(key, '=' , fiber1[key])
name = E-glass
rho = 2.55
E = 72.5
TS = 3400.0

Dictionaries are dynamic and we may add items by the following methods:

In [4]:
fiber1['price']=1.2                         # alternative 1, single item

fiber1.update({'CTE':8.0, 'diam':14.0 })    # alternative 2, multiple items

for key in fiber1:
    print(key, '=' , fiber1[key])
name = E-glass
rho = 2.55
E = 72.5
TS = 3400.0
price = 1.2
CTE = 8.0
diam = 14.0

Tuples and Lists

Tuples are fixed size whereas lists are dynamic. In other words, a tuple is immutable whereas a list is mutable.

In [5]:
someNumbersA=(4,5,6)  # Tuple
someNumbersB=[7,8,9]  # List

someNumbersB.append(10)

print(someNumbersA)
print(someNumbersB)
(4, 5, 6)
[7, 8, 9, 10]

Both tuples and lists may contain any other data types, for instance dictionaries:

In [6]:
fiber1={'name':'E-glass' , 'rho':2.55 , 'E': 72.5 , 'TS':3400.0}
fiber2={'name':'S-glass' , 'rho':2.45 , 'E': 78.5 , 'TS':4500.0}
fiber3={'name':'Carbon'  , 'rho':1.78 , 'E':235.0 , 'TS':3600.0}

fibers=[fiber1,fiber2,fiber3]

Access to items (remember that indexing in Python starts with zero):

In [7]:
print( fibers[0]['name'])   # first item in the list
print( fibers[-1]['name'])  # last item in the list
print( len(fibers))         # length of the list
E-glass
Carbon
3

Iteration methods:

In [8]:
for fiber in fibers:
    print(fiber['rho'])
2.55
2.45
1.78
In [9]:
for i in range(0, len(fibers)):
    print(fibers[i]['E'])
72.5
78.5
235.0

A list can be created using a generator. For example, range() is a generator, such that:

In [10]:
n = list(  range(0,10)  )
print (n)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

A featured Pytonic method is to use expression acting as a generator in the list construction as in this example:

In [11]:
p = [x**2 for x in range(0,10)]
print(p)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

NumPy

NumPy is the fundamental package for scientific computing with Python. A recomended start is the basic tutorial from scipy.org.

The most frequently used NumPy methods relevant for this course are presented during the following examples. Note however that if you really want to understand and master NumPy, you will need to study the documentation.

NumPy is accessed by import numpy. It is quite common to use the alias np as written in the first line:

In [12]:
import numpy as np
from numpy import dot
from numpy.linalg import inv as minv

Sometimes it is convenient to import just individual functions, such as dot given as an example in the second line. NumPy, as a package, contains several modules. The linalg module is about linear algebra, where inv is a function that computes the inverse of a matrix.

Creating Arrays

There are several ways to create arrays. For example, you can create an array from a regular Python list or tuple using the array function, or you can use various functions that generates arrays, or arrays can be read from files.

array()

The function do a conversion from other Python structures (e.g., lists, tuples). The type of the resulting array is deduced from the type of the elements in the sequences.

A one-dimentional array having 3 items (in this case integers) can be created by:

In [13]:
a1 = np.array([1,2,3])

print(a1)
[1 2 3]

Observe that the argument of array in the previous example is a list. The array could alternatively be created by:

In [14]:
alist = [1,2,3]
a1 = np.array(alist)

print(a1)
[1 2 3]

A tuple can be used as well:

In [15]:
a2 = np.array( (4,5,6) )

print(a2)
[4 5 6]

Creating a 2-dimentional array from existing lists:

In [16]:
blist1 = [1,2,3]
blist2 = [4,5,6]
blist3 = [7,8,9]

b1 = np.array([blist1,blist2,blist3])

print(b1)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

The above implementation is equal to:

In [17]:
b1 = np.array([[1,2,3],
               [4,5,6],
               [7,8,9]])

print(b1)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

zeros(shape) will create an array filled with 0 values with the specified shape. The default dtype is float64.

ones(shape) will create an array filled with 1 values. It is identical to zeros in all other respects.

identity(n) creates an array n x n with ones on its diagonal.

In [18]:
c1 = np.zeros( (3,3) )
print(c1)
print()

c2 = np.ones( (2,5) )
print(c2)
print()

c3 = np.identity(3)
print(c3)
print()
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]]

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

Creating an array of six numbers, from zero to (and including) 10:

In [19]:
k1 = np.linspace(start=0,stop=10,num=6, dtype=int)
print(k1)
[ 0  2  4  6  8 10]

Note that we do not need to include endpoint = True since that is default.

A similar result can be obtained using arange():

arange(start, stop, step, dtype=None)

In [20]:
k2 = np.arange(start=0,stop=12,step=2)
print(k2)
[ 0  2  4  6  8 10]

Note that stop is not included in the array.

Decending arrays can be created as well:

In [21]:
k3 = np.linspace(start=100,stop=0,num=11, dtype=int)
print(k3)
[100  90  80  70  60  50  40  30  20  10   0]

Array manipulation

Examples of array manipulation methods:

reshape(a, newshape)

In [22]:
h1=np.linspace(start=1,stop=12,num=12)

print(h1)
print()

h2=np.reshape(h1,(3,4))

print(h2)
[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12.]

[[ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 9. 10. 11. 12.]]

transpose(a)

In [23]:
h3=np.transpose(h2)

print(h3)
[[ 1.  5.  9.]
 [ 2.  6. 10.]
 [ 3.  7. 11.]
 [ 4.  8. 12.]]

stack((a1, a2,..), axis=0)

In [24]:
j1=np.array([1,2,3])
j2=np.array([4,5,6])

j3=np.stack((j1,j2),axis=0)
print(j3)
[[1 2 3]
 [4 5 6]]
In [25]:
j4=np.stack((j1,j2),axis=1)
print(j4)
[[1 4]
 [2 5]
 [3 6]]

concatenate((a1, a2, ...), axis=0)

In [26]:
j5=np.concatenate((j3,j3),axis=0)
print(j5)
[[1 2 3]
 [4 5 6]
 [1 2 3]
 [4 5 6]]
In [27]:
j6=np.concatenate((j3,j3),axis=1)
print(j6)
[[1 2 3 1 2 3]
 [4 5 6 4 5 6]]

Indexing and Slicing

Examples of indexing and Slicing:

In [28]:
a = np.linspace(start=1,stop=36,num=36)
A = np.reshape(a,(6,6))
print(A)
[[ 1.  2.  3.  4.  5.  6.]
 [ 7.  8.  9. 10. 11. 12.]
 [13. 14. 15. 16. 17. 18.]
 [19. 20. 21. 22. 23. 24.]
 [25. 26. 27. 28. 29. 30.]
 [31. 32. 33. 34. 35. 36.]]
In [29]:
A1 = A[0:3,0:3]
print(A1)
[[ 1.  2.  3.]
 [ 7.  8.  9.]
 [13. 14. 15.]]
In [30]:
A2 = A[:,5]
print(A2)
[ 6. 12. 18. 24. 30. 36.]
In [31]:
A3=A[2:4,:]
print(A3)
[[13. 14. 15. 16. 17. 18.]
 [19. 20. 21. 22. 23. 24.]]
In [32]:
A4=A[2:4,2:4]
print(A4)
[[15. 16.]
 [21. 22.]]

Linear algebra

dot(a1,a2)

Dot product of two arrays is obtained by dot(a1,a2).

Example: Transformation of coordinates by clock-wise rotation about the z-axis is given by

\begin{equation} \begin{bmatrix} x' \\ y' \\ z' \end{bmatrix}= \begin{bmatrix} c & s & 0 \\ -s & c & 0 \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ z \end{bmatrix} \end{equation}

The transformation matrix for a given angle can be created by:

In [33]:
from math import cos,sin,radians

angle=30

c=cos(radians(angle))
s=sin(radians(angle))

T = np.array([[ c,s,0],
              [-s,c,0],
              [ 0,0,1]])

print(T)
[[ 0.8660254  0.5        0.       ]
 [-0.5        0.8660254  0.       ]
 [ 0.         0.         1.       ]]
In [34]:
xyz = [1,2,0]

xyz_transformed = np.dot(T,xyz)

print(xyz_transformed)
[1.8660254  1.23205081 0.        ]

linalg.inv(a)

The (multiplicative) inverse of a matrix.

In [35]:
T_inv = np.linalg.inv(T)
print(T_inv)
[[ 0.8660254 -0.5        0.       ]
 [ 0.5        0.8660254  0.       ]
 [ 0.         0.         1.       ]]
In [36]:
xyz = np.dot(T_inv, xyz_transformed)
print(xyz)
[1. 2. 0.]

Mathematical functions and operators on NumPy arrays

Generally, the mathematical functions returns element-wise results.

Some examples that will be relevant in the course:

In [37]:
i = np.linspace(start=0,stop=5,num=6)
print(i)
[0. 1. 2. 3. 4. 5.]
In [38]:
c = np.cos(i/10)
s = np.sin(i/10)
print(c)
print(s)
[1.         0.99500417 0.98006658 0.95533649 0.92106099 0.87758256]
[0.         0.09983342 0.19866933 0.29552021 0.38941834 0.47942554]
In [39]:
c_round = np.round(c,2)
print(c_round)
[1.   1.   0.98 0.96 0.92 0.88]
In [40]:
p = np.power(i,2)
print(p)
[ 0.  1.  4.  9. 16. 25.]
In [41]:
cs=np.multiply(c,s)
print(cs)
[0.         0.09933467 0.19470917 0.28232124 0.35867805 0.42073549]
In [42]:
cs2=c*s
print(cs2)
[0.         0.09933467 0.19470917 0.28232124 0.35867805 0.42073549]
In [43]:
c2s2=(c**2)+(s**2)
print(c2s2)
[1. 1. 1. 1. 1. 1.]

Visualization using Matplotlib

There are obviously cases where the quantiative result of a scientific or technical problem is best presented as just one or a few numbers. However, for a vide range of problems involving larger quantities of data, graphical such as a chart helps the human brain to make sense of the data. Charts are often used to ease understanding of large quantities of data and the relationships between parts of the data.

In TMM4175 Polymer Composites we will be using Matplotlib for Python extensivly. Examples of the capabilities of Matplotlib can be seen in the Gallery

Matplotlib comes with the Anaconda package.

A collection of plots developed for this course can be found in the Plot Gallery.

Import statements

Import of Matplotlib for Python:

In [44]:
import matplotlib.pyplot as plt

If you are using Python Notebook and intend to have figurs apparing inline in the notebook, you will need to add

In [45]:
%matplotlib inline

Simple line plots examples

In [46]:
import numpy as np
t =  np.linspace(start=0,stop=2*np.pi,num=50)
y1 = np.cos(t)
y2 = np.sin(t)

plt.plot(t,y1,t,y2)
plt.show()
In [47]:
fig,ax = plt.subplots(nrows=1,ncols=1, figsize = (5,3))
ax.plot(t,y1)
ax.plot(t,y2)
plt.show()
In [48]:
fig,(ax1,ax2) = plt.subplots(nrows=1,ncols=2, figsize = (7,2))
ax1.plot(t,y1)
ax2.plot(t,y2)
plt.show()
In [49]:
fig,axs = plt.subplots(nrows=2,ncols=2, figsize = (7,5))
axs[0,0].plot(t,y1)
axs[0,1].plot(t,y2)
axs[1,0].plot(t,y1**2)
axs[1,1].plot(t,y2*y1)
plt.show()
In [50]:
fig,ax = plt.subplots(nrows=1,ncols=1, figsize = (5,3))
ax.plot(t,y1,'--',color='red')
ax.plot(t,y2,'-.',color='blue')
ax.grid(True)
ax.set_xlim(0,2*np.pi)
plt.show()
In [51]:
fig,ax = plt.subplots(nrows=1,ncols=1, figsize = (5,3))
ax.plot(t,y1,'--',color='red',label='cos')
ax.plot(t,y2,'-.',color='blue',label='sin')
ax.grid(True)
ax.set_xlim(0,2*np.pi)
ax.legend(loc='best')
ax.set_title('Waves')
ax.set_xlabel('Time',size=12)
ax.set_ylabel('Amplitude',size=12)

plt.show()

See the Plot gallery for more examples used in TMM4175 Polymer Composites

Disclaimer:This site is about polymer composites, designed for educational purposes. Consumption and use of any sort & kind is solely at your own risk.
Fair use: I spent some time making all the pages, and even the figures and illustrations are my own creations. Obviously, you may steal whatever you find useful here, but please show decency and give some acknowledgment if or when copying. Thanks! Contact me: nils.p.vedvik@ntnu.no www.ntnu.edu/employees/nils.p.vedvik

Copyright 2021, All right reserved, I guess.